package kr.co.graviti.common.application;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import kr.co.graviti.common.exception.UploadFileAllowException;
import kr.co.graviti.common.exception.UploadFileNotAllowException;
import kr.co.graviti.common.model.MultipartUploadFile;
import kr.co.graviti.common.model.MultipartUploadFileRepository;
import kr.co.graviti.common.util.CommonUtil;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

@Service
public class MultipartUploadFileService {

	@Resource
	private MultipartUploadFileRepository multipartUploadFileRepository;
	
	public MultipartUploadFileService() {}
	
	public MultipartUploadFileService(MultipartUploadFileRepository multipartUploadFileRepository) {
		this.multipartUploadFileRepository = multipartUploadFileRepository;
	}
	
	public MultipartUploadFile[] regist(String prefix,String uploadPath
			, long uploadSize
			, String uploadAllowPostfix
			, List<MultipartFile> multipartfileList) {
		
		if (multipartfileList == null || multipartfileList.size() == 0)
			return new MultipartUploadFile[]{};
		
		ArrayList arraylist = new ArrayList();
		for (int i = 0; i < multipartfileList.size(); i ++) {
			MultipartUploadFile multipartUploadFile = regist(prefix ,uploadPath
					, uploadSize
					, uploadAllowPostfix
					, (MultipartFile)multipartfileList.get(i));
			
			arraylist.add(multipartUploadFile);
		}
		
		return (MultipartUploadFile[])arraylist.toArray(new MultipartUploadFile[0]);
	}
	
	public MultipartUploadFile regist(String prefix,String uploadPath
			, long uploadSize
			, String uploadAllowPostfix
			, MultipartFile multipartfile) {
		
		MultipartUploadFile multipartUploadFile = new MultipartUploadFile();
		
		File f = new File(uploadPath);
		if (!f.exists()) f.mkdir();
		
		if (multipartfile == null || multipartfile.isEmpty())
			return new MultipartUploadFile();
		
		if (uploadSize < multipartfile.getSize())
			throw new UploadFileAllowException("첨부파일의 허용용량을 초과하였습니다.");
		
		if (uploadAllowPostfix != null && !CommonUtil.contains(
				CommonUtil.toLowerCase(CommonUtil.getLast(multipartfile.getOriginalFilename(), ".")), 
				CommonUtil.divideStringArray(CommonUtil.toLowerCase(uploadAllowPostfix), ","))) {
			
			throw new UploadFileNotAllowException("해당 파일의 확장자는 첨부할 수 없습니다.");
		}
		
		multipartUploadFile = multipartUploadFileRepository.registFile(prefix,uploadPath, multipartfile);
		
		return multipartUploadFile;
	}
	
	public void delete(String uploadPath, String filename) {
		File file = new File(uploadPath, filename);
		
		if (file.exists())
			file.delete();
	}
	
	public String binaryUpload(String destinationUrl
			, String uploadPath
			, String serviceCode, long photoId) {
		
		return binaryUpload(destinationUrl, uploadPath, serviceCode, photoId, "file");
	}
	
	public String binaryUpload(String destinationUrl, String uploadPath, String serviceCode, long photoId, String gubun) {
		
		if ("file".equals(gubun)) 
			destinationUrl += "binary/"+serviceCode+"/"+photoId+"/"+getFileExtention(uploadPath);
		else 
			destinationUrl += "image/"+serviceCode+"/"+photoId;
		
		HttpClient httpclient = new HttpClient();
		httpclient.getParams().setParameter("http.protocol.content-charset", "utf-8");
		
		PostMethod method = new PostMethod(destinationUrl);
		
		String uploadedUrl = null;
		InputStream is = null;
		
		try {
			File f = new File(uploadPath);
			
			Part[] parts = {
				new FilePart("file", f, "text/html; charset=UTF-8", "UTF-8")
			};
			method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams()));
			
			int status = httpclient.executeMethod(method);
			
			if (status == HttpStatus.SC_OK) {
				is = method.getResponseBodyAsStream();
//				uploadUrl = (String) xStream.fromXML(is);
			}
			
			if (f.exists())
				f.delete();
	
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		} finally {
			if (is != null) {
				try {
					is.close();
				} catch (IOException e2) {
					e2.printStackTrace();
					// TODO: handle exception
				}
			}
		}
		
		return uploadedUrl;
	}
	
	public static String getFileExtention(String s) {
		if (s.indexOf(".") > 0)
			s = s.substring(s.lastIndexOf(".")+1);
		return s;
	}
	
}
